package cn.edu.zjicm.wordsnet_d.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.adapter.AddSchoolAdapter;
import cn.edu.zjicm.wordsnet_d.adapter.WordBookForListAdapter;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference.BookType;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.synchronize.PayInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;
import cn.edu.zjicm.wordsnet_d.view.PayDialog;

import com.umeng.analytics.MobclickAgent;

public class SelectBookActivity extends WordBaseActivity {

	private ArrayList<Integer> selectedBookIndexs = null;

	protected Integer bookID = -1;

	public static int INIT_MODE2 = 2; // 从引导页面进来，需要返回键

	public static boolean fromAlipay; // 是否进入过阿里支付返回到此界面

	private int startMode;
	private int bookType;
	private SparseArray<String> bookClassMap; // 该类别下单词书个数
	private List<Integer> list1;
	private SparseArray<List<Integer>> allClassMap; // 存放单词书的List
	private String[] classStr = new String[] { "初中", "初中教材配套", "高中", "高中教材配套", "大学", "专业英语", "出国考试", "新概念英语" };
	private int[] allBooksIndex = AppPreference.Book.BOOK_INDEX; // 所有的单词书id
	private int preBookClassIndex = -1; // 在配套中，上一级的书类别

	private WordBookForListAdapter adapter1;
	private ListView bookLv, bookLv2; // bookLv2在教材配套里用到
	private ViewFlipper mFlipper;
	private ListView mListView;
	private TextView bookClass;
	private PayDialog payDialog;
	private TextView noBookHint;
	private ViewFlipper bookFlipper;
	private WordFactory mFactory;

	public static SelectBookActivity mInstance;

	public static void mStartActivity(Context mContext, int startMode) {
		Intent in = new Intent(mContext, SelectBookActivity.class);
		in.putExtra("startMode", startMode);
		mContext.startActivity(in);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_book);
		mInstance = SelectBookActivity.this;
		startMode = getIntent().getIntExtra("startMode", StaticData.MODE_INIT);
		bookType = getIntent().getIntExtra("bookType", AppPreference.BookType.BOOK_WORD);

		setTitleBarStyle(WordBaseActivity.TITLE_BAR_STYLE_BACK_BUTTON);
		if (StaticData.MODE_INIT == startMode) {
			setTitleText("设置学习计划");
			hideTitleBarBackButton2();
		} else {
			setTitleText("选择词汇书");
		}

		setBackButton(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toFinish();
			}
		});

		findView();
		initView();

		getProductList();
	}

	private void findView() {
		bookLv = (ListView) findViewById(R.id.book_lv);
		mFlipper = (ViewFlipper) findViewById(R.id.select_book_flipper);
		mListView = (ListView) findViewById(R.id.select_book_lv);
		bookClass = (TextView) findViewById(R.id.select_book_class);
		noBookHint = (TextView) findViewById(R.id.no_book_hint);
		bookFlipper = (ViewFlipper) findViewById(R.id.book_flipper);
		bookLv2 = (ListView) findViewById(R.id.book_lv2);
	}

	private void initView() {
		mFactory = WordFactory.getInstance(mInstance);

		if (bookType == AppPreference.BookType.BOOK_WORD) { // 单词书
			allClassMap = new SparseArray<List<Integer>>();
			bookClassMap = new SparseArray<String>();
			for (int i = 0; i < classStr.length; i++) {
				setWordBookData(i);
				allClassMap.put(i, list1);

				int publishSize = 0;

				if (i == 1) {
					for (int j = 0; j < AppPreference.Book.PUBLISH_INDEX_JUNIOR.length; j++) {
						setWordBookData(100 + j);
						allClassMap.put(100 + j, list1);
						bookClassMap.put(100 + j, AppPreference.Book.PUBLISH_NAME_JUNIOR[j] + "(" + list1.size() + ")");
						publishSize += list1.size();
					}
					bookClassMap.put(i, classStr[i] + "(" + publishSize + ")");
				} else if (i == 3) {
					for (int j = 0; j < AppPreference.Book.PUBLISH_INDEX_SENIOR.length; j++) {
						setWordBookData(300 + j);
						allClassMap.put(300 + j, list1);
						bookClassMap.put(300 + j, AppPreference.Book.PUBLISH_NAME_SENIOR[j] + "(" + list1.size() + ")");
						publishSize += list1.size();
					}
					bookClassMap.put(i, classStr[i] + "(" + publishSize + ")");
				} else {
					bookClassMap.put(i, classStr[i] + "(" + list1.size() + ")");
				}
			}

			List<String> bookClassList = new ArrayList<String>();
			for (int i = 0; i < classStr.length; i++) {
				bookClassList.add(bookClassMap.get(i));
			}

			AddSchoolAdapter adapter = new AddSchoolAdapter(this, bookClassList, true);
			mListView.setAdapter(adapter);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					displayBook(position);
				}
			});
		} else { // 词组书
			setPhraseBookData();
			mFlipper.setDisplayedChild(1);
			bookClass.setText("词组书(" + list1.size() + ")");
			setPhraseBookAdapter();
		}
	}

	protected void displayBook(int position) {
		mFlipper.setDisplayedChild(1);
		bookClass.setText(bookClassMap.get(position));
		setWordBookAdapter(position);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		if (bookID != -1 && mFactory.getPrice(bookID) > 0 && UserInterface.getInstance(this).isLogin()) {
			if (fromAlipay) {
				if (payDialog == null) {
					payDialog = new PayDialog(this, bookID);
				} else {
					payDialog.resetBalance();
				}
			} else {
				if (payDialog != null) {
					payDialog.cancel();
					payDialog = null;
				}
			}
		}
		fromAlipay = false;
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	protected void saveBookIndex(Integer bookIndex2) {
		if (mFactory.getPrice(bookIndex2) > 0 && !mFactory.isBought(bookIndex2)) { // 需要收费并且未购买过
			if (!UserInterface.getInstance(this).isLogin()) {
				showHintLoginDialog();
			} else {
				payDialog = new PayDialog(this, bookIndex2);
			}
		} else {
			toFinish2();
		}
	}

	private void showHintLoginDialog() {
		View view = LayoutInflater.from(this).inflate(R.layout.view_dialog_normal, null);
		Button cancel = (Button) view.findViewById(R.id.dialog_btn_ok);
		Button toLogin = (Button) view.findViewById(R.id.dialog_btn_cancel);
		TextView content = (TextView) view.findViewById(R.id.dialog_content);
		cancel.setText("取消");
		toLogin.setText("前往登录");
		content.setText("只有登录帐号以后才能学习词组哦");
		final MyDialog hintLoginDialog = new MyDialog(this, view, R.style.mydialog, false);
		hintLoginDialog.show();
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				hintLoginDialog.dismiss();
			}
		});
		toLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				RegisterActivity.startActivity(SelectBookActivity.this, RegisterActivity.TO_PAY);
				hintLoginDialog.dismiss();
			}
		});
	}

	private void setWordBookData(int position) {
		list1 = new ArrayList<Integer>();
		switch (position) {
		case 0: // 初中
			list1.add(allBooksIndex[7]);
			break;
		case 1: // 初中配套教材
			for (int i = 0; i < AppPreference.Book.PUBLISH_INDEX_JUNIOR.length; i++) {
				list1.add(AppPreference.Book.PUBLISH_INDEX_JUNIOR[i]);
			}
			break;
		case 2: // 高中
			list1.add(allBooksIndex[6]);
			list1.add(allBooksIndex[3]);
			list1.add(allBooksIndex[4]);
			break;
		case 3: // 高中配套教材
			for (int i = 0; i < AppPreference.Book.PUBLISH_INDEX_SENIOR.length; i++) {
				list1.add(AppPreference.Book.PUBLISH_INDEX_JUNIOR[i]);
			}
			break;
		case 4:// 大学
			list1.add(allBooksIndex[0]);
			list1.add(allBooksIndex[15]);
			list1.add(allBooksIndex[1]);
			list1.add(allBooksIndex[16]);
			list1.add(allBooksIndex[2]);
			list1.add(allBooksIndex[17]);
			list1.add(allBooksIndex[5]);
			break;
		case 5: // 专业英语
			list1.add(allBooksIndex[10]);
			list1.add(allBooksIndex[22]);
			break;
		case 6: // 出国考试
			list1.add(allBooksIndex[8]);
			list1.add(allBooksIndex[9]);
			list1.add(allBooksIndex[112]);
			break;
		case 7: // 新概念英语
			list1.add(allBooksIndex[11]);
			list1.add(allBooksIndex[12]);
			list1.add(allBooksIndex[13]);
			list1.add(allBooksIndex[14]);
			break;

		case 100: // 人教版
			list1.add(allBooksIndex[73]);
			list1.add(allBooksIndex[23]);
			list1.add(allBooksIndex[74]);
			list1.add(allBooksIndex[31]);
			list1.add(allBooksIndex[39]);
			break;
		case 101: // 外研社
			list1.add(allBooksIndex[78]);
			list1.add(allBooksIndex[24]);
			list1.add(allBooksIndex[79]);
			list1.add(allBooksIndex[32]);
			list1.add(allBooksIndex[80]);
			list1.add(allBooksIndex[40]);
			break;
		case 102: // 牛津上海
			list1.add(allBooksIndex[64]);
			list1.add(allBooksIndex[26]);
			list1.add(allBooksIndex[65]);
			list1.add(allBooksIndex[34]);
			list1.add(allBooksIndex[66]);
			list1.add(allBooksIndex[42]);
			break;
		case 103:// 牛津深圳
			list1.add(allBooksIndex[67]);
			list1.add(allBooksIndex[27]);
			list1.add(allBooksIndex[68]);
			list1.add(allBooksIndex[35]);
			list1.add(allBooksIndex[69]);
			list1.add(allBooksIndex[43]);
			break;
		case 104:// 牛津译林
			list1.add(allBooksIndex[70]);
			list1.add(allBooksIndex[25]);
			list1.add(allBooksIndex[71]);
			list1.add(allBooksIndex[33]);
			list1.add(allBooksIndex[72]);
			list1.add(allBooksIndex[41]);
			break;
		case 105:// 冀教
			list1.add(allBooksIndex[81]);
			list1.add(allBooksIndex[28]);
			list1.add(allBooksIndex[36]);
			break;
		case 106:// 仁爱
			list1.add(allBooksIndex[75]);
			list1.add(allBooksIndex[29]);
			list1.add(allBooksIndex[76]);
			list1.add(allBooksIndex[37]);
			list1.add(allBooksIndex[77]);
			list1.add(allBooksIndex[44]);
			break;
		case 107:// 北师大
			list1.add(allBooksIndex[57]);
			list1.add(allBooksIndex[30]);
			list1.add(allBooksIndex[58]);
			list1.add(allBooksIndex[38]);
			break;
		case 108:// 鲁教
			list1.add(allBooksIndex[59]);
			list1.add(allBooksIndex[60]);
			list1.add(allBooksIndex[61]);
			list1.add(allBooksIndex[62]);
			list1.add(allBooksIndex[63]);
			break;

		case 300:// 人教
			list1.add(allBooksIndex[91]);
			list1.add(allBooksIndex[45]);
			list1.add(allBooksIndex[92]);
			list1.add(allBooksIndex[50]);
			list1.add(allBooksIndex[93]);
			break;
		case 301:// 外研
			list1.add(allBooksIndex[94]);
			list1.add(allBooksIndex[46]);
			list1.add(allBooksIndex[51]);
			break;
		case 302: // 牛津译林
			list1.add(allBooksIndex[85]);
			list1.add(allBooksIndex[47]);
			list1.add(allBooksIndex[86]);
			list1.add(allBooksIndex[52]);
			list1.add(allBooksIndex[87]);
			list1.add(allBooksIndex[55]);
			break;
		case 303:// 牛津上海
			list1.add(allBooksIndex[88]);
			list1.add(allBooksIndex[48]);
			list1.add(allBooksIndex[89]);
			list1.add(allBooksIndex[53]);
			list1.add(allBooksIndex[90]);
			list1.add(allBooksIndex[56]);
			break;
		case 304:// 北师大
			list1.add(allBooksIndex[82]);
			list1.add(allBooksIndex[49]);
			list1.add(allBooksIndex[83]);
			list1.add(allBooksIndex[54]);
			list1.add(allBooksIndex[84]);
			break;
		case 305:// 新世纪
			list1.add(allBooksIndex[95]);
			list1.add(allBooksIndex[96]);
			list1.add(allBooksIndex[97]);
			list1.add(allBooksIndex[98]);
			list1.add(allBooksIndex[99]);
			list1.add(allBooksIndex[100]);
			break;
		}
		int selectWordBookIndex = AppPreference.getWordBookIndex(this);
		if (list1.contains(selectWordBookIndex)) {
			list1.remove(list1.indexOf(selectWordBookIndex));
		}
	}

	private void setPhraseBookData() {
		list1 = new ArrayList<Integer>();

		list1.add(allBooksIndex[18]);
		list1.add(allBooksIndex[19]);
		list1.add(allBooksIndex[101]);
		list1.add(allBooksIndex[106]);
		list1.add(allBooksIndex[103]);
		list1.add(allBooksIndex[104]);
		list1.add(allBooksIndex[108]);
		list1.add(allBooksIndex[110]);

		int selectPhraseBookIndex = AppPreference.getPhraseBookIndex(this);
		if (list1.contains(selectPhraseBookIndex)) {
			list1.remove(list1.indexOf(selectPhraseBookIndex));
		}
	}

	List<Integer> list;

	private void setPhraseBookAdapter() {
		if (list1.size() == 0) {
			bookFlipper.setVisibility(View.GONE);
			noBookHint.setVisibility(View.VISIBLE);
		} else {
			bookFlipper.setVisibility(View.VISIBLE);
			noBookHint.setVisibility(View.GONE);
			adapter1 = new WordBookForListAdapter(list1, this, false, false, false);
			setMarginBottom(bookLv);
			bookLv.setAdapter(adapter1);
			bookLv.setSelector(new ColorDrawable(Color.TRANSPARENT));
			bookLv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					bookID = list1.get(position);
					int unlearnedWordCount = mFactory.getUnLearnedWordCount(bookID);
					if (unlearnedWordCount != 0) {
						saveBookIndex(bookID);
					}
				}
			});
		}
	}

	private void setWordBookAdapter(final int position1) {
		long start = System.currentTimeMillis();
		list = allClassMap.get(position1);

		if (list.size() == 0) {
			bookFlipper.setVisibility(View.GONE);
			noBookHint.setVisibility(View.VISIBLE);
		} else {
			bookFlipper.setVisibility(View.VISIBLE);
			noBookHint.setVisibility(View.GONE);
			if (position1 == 1) {
				adapter1 = new WordBookForListAdapter(list, this, true, false, true);
			} else if (position1 == 3) {
				adapter1 = new WordBookForListAdapter(list, this, true, false, false);
			} else {
				adapter1 = new WordBookForListAdapter(list, this, false, false, false);
			}

			setMarginBottom(bookLv);
			bookLv.setAdapter(adapter1);
			bookLv.setSelector(new ColorDrawable(Color.TRANSPARENT));
			bookLv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position2, long id) {
					if (position1 == 1 || position1 == 3) {
						setAdapter2(position1, position2);
					} else {
						bookID = list.get(position2);
						if (mFactory.getUnLearnedWordCount(bookID) != 0) {
							saveBookIndex(bookID);
						}
					}
				}
			});
		}

		LogUtil.d("Tag", "setAdapter中,用时:" + (System.currentTimeMillis() - start));
	}

	private void setMarginBottom(ListView mListView) {
		if (mListView.getFooterViewsCount() == 0) {
			View footView = new View(this);
			AbsListView.LayoutParams vl = new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, Utils.changeDipToPx(this, 15));
			footView.setLayoutParams(vl);
			mListView.addFooterView(footView);
		}
	}

	private void setAdapter2(final int classPositon, int publishPosition) {
		bookFlipper.setDisplayedChild(1);

		preBookClassIndex = classPositon;

		if (classPositon == 1) {
			list = allClassMap.get(100 + publishPosition);
			bookClass.setText(bookClassMap.get(100 + publishPosition));
		} else if (classPositon == 3) {
			list = allClassMap.get(300 + publishPosition);
			bookClass.setText(bookClassMap.get(300 + publishPosition));
		}

		if (list.size() == 0) {
			bookFlipper.setDisplayedChild(1);
			bookFlipper.setVisibility(View.GONE);
			noBookHint.setVisibility(View.VISIBLE);
		} else {
			bookFlipper.setVisibility(View.VISIBLE);
			noBookHint.setVisibility(View.GONE);

			setMarginBottom(bookLv2);
			adapter1 = new WordBookForListAdapter(list, this, false, true, false);

			bookLv2.setAdapter(adapter1);
			bookLv2.setSelector(new ColorDrawable(Color.TRANSPARENT));
			bookLv2.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					bookID = list.get(position);
					int unlearedWordCount = mFactory.getUnLearnedWordCount(bookID);
					if (unlearedWordCount != 0) {
						saveBookIndex(bookID);
					}
				}
			});
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			toFinish();
			return true;
		}
		return false;
	}

	public void toFinish() {
		if (bookType == AppPreference.BookType.BOOK_WORD && mFlipper.getDisplayedChild() == 1) {
			if (bookFlipper.getDisplayedChild() == 1) {
				bookFlipper.setDisplayedChild(0);
				bookFlipper.setVisibility(View.VISIBLE);
				noBookHint.setVisibility(View.GONE);
				bookClass.setText(bookClassMap.get(preBookClassIndex));
			} else {
				bookFlipper.setDisplayedChild(0);
				mFlipper.setDisplayedChild(0);
			}
		} else {
			finishActivity();
		}
	}

	public void toFinish2() {

		String bookClassStr = bookClass.getText().toString();
		int end = bookClassStr.indexOf("(");
		bookClassStr = bookClassStr.substring(0, end);

		if (startMode == StaticData.MODE_INIT || startMode == INIT_MODE2) {
			SelectStudyModeActivity.startActivity(mInstance, bookID, bookClassStr, BookType.BOOK_WORD); // 一开始只能选择单词书
		} else if (startMode == StaticData.MODE_UPDATE) {
			Intent intent = new Intent(mInstance, SelectStudyModeActivity.class);
			intent.putExtra("bookIndex", bookID);
			intent.putExtra("bookClass", bookClassStr);
			intent.putExtra("bookType", bookType);
			intent.putExtra("startMode", StaticData.MODE_UPDATE);
			startActivityForResult(intent, StaticData.requestCode);
		}

	}

	public void finishActivity() {
		finish();
		mInstance = null;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == StaticData.requestCode && resultCode == StaticData.resultCode) {
			this.setResult(resultCode, intent);
			finish();
		}
	}

	void getProductList() {
		// getProductListHandler.sendMessage(getProductListHandler.obtainMessage(UserInterface.MSG_START));
		PayInterface.getInstance(this).getCommodityList(getProductListHandler);
	}

	Handler getProductListHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}
			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(SelectBookActivity.this, null, "正在获取商品信息");
				break;
			case UserInterface.MSG_SUCCESS:
				if (adapter1 != null)
					adapter1.notifyDataSetChanged();
				break;
			case UserInterface.MSG_UNSUCCESS:
				break;
			case UserInterface.MSG_BAD_NETWORK:
				break;
			case UserInterface.MSG_WEB_SITE_ERROR:
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				break;
			}
		};
	};

}
